<script setup>
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { REQU, toFormData, useResp } from '@/net/requ';

const props = defineProps(['visible', 'role']);
const emit = defineEmits(['update:visible', 'ok']);

const visible = ref(props.visible);
watch(visible, value => emit('update:visible', value));

const formElem = ref();

const rules = {
  roleName: [ { required: true, message: '请输入角色名称' } ],
  roleCode: [ { required: true, message: '请输入角色 code' } ],
};

const FormState = () => ({ roleName: '', roleCode: '' });

const formState = ref(Object.assign(FormState(), props.role));

function save() {
  return REQU('/api/role/save', {
    method: 'POST',
    body: toFormData(formState.value),
  })
  .then(useResp({
    succ: result => {
      message.success('保存成功');
      return result;
    },
    fail: result => {
      message.error(result.message || '保存失败');
      return result;
    },
  }))
}

function onOk() {
  formElem.value
  .validate()
  .then(save)
  .then(result => {
    if (200 == result.code) {
      emit('ok');
      emit('update:visible', false);
    }
  })
  .catch(() => {});
}
</script>

<template>
  <a-modal
    :width="384"
    :visible="visible"
    :title="`${ formState.id ? '编辑' : '新建' }角色`"
    @cancel="visible = false"
    @ok="onOk">
    <a-form
      ref="formElem"
      layout="vertical"
      :rules="rules"
      :model="formState">
      <a-form-item required label="角色名称" name="roleName">
        <a-input v-model:value="formState.roleName" placeholder="请输入角色名称"></a-input>
      </a-form-item>
      <a-form-item required label="角色 code" name="roleCode">
        <a-input v-model:value="formState.roleCode" placeholder="请输入角色 code"></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
